package com.example.everying.service.content.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.everying.constant.RatingConstants;
import com.example.everying.constant.RatingRole;
import com.example.everying.context.UserContext;
import com.example.everying.mapper.content.ActivityRatingMapper;
import com.example.everying.model.dto.content.ActivityRatingDto;
import com.example.everying.model.entity.ActivityRating;
import com.example.everying.model.entity.content.ActivityArticle;
import com.example.everying.model.vo.content.ActivityArticleVo;
import com.example.everying.model.vo.user.UserInfoVo;
import com.example.everying.service.content.ActivityApplyService;
import com.example.everying.service.content.ActivityArticleService;
import com.example.everying.service.content.ActivityRatingService;
import com.example.everying.service.user.UserScoreService;
import com.example.everying.service.user.UserService;
import com.example.everying.utils.CampusException;
import com.example.everying.utils.RandomUtil;
import com.example.everying.utils.Result;
import com.example.everying.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 活动评价服务实现类
 */
@Service
public class ActivityRatingServiceImpl extends ServiceImpl<ActivityRatingMapper, ActivityRating> implements ActivityRatingService {

    @Autowired
    private ActivityArticleService activityArticleService;
    @Autowired
    private ActivityApplyService activityApplyService;
    @Autowired
    private UserScoreService userScoreService;


    /**
     * 新增评价（完整逻辑）
     *
     * @param rating 评价对象
     * @return 操作结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveRating(ActivityRating rating) {
        // 1. 参数校验
        validateRating(rating);

        // 2. 获取关联活动
        ActivityArticle article = activityArticleService.getById(rating.getArticleId());
        if (article == null) {
            throw new CampusException("关联活动不存在", 201);
        }

        // 3. 校验活动状态是否允许评价
        if (!canRateArticle(article)) {
            throw new CampusException("当前活动状态不允许评价", 201);
        }

        // 4. 设置评价角色
        if (article.getUserId().equals(rating.getRaterId())) {
            rating.setRatingRole(RatingRole.PUBLISHER_TO_PARTICIPANT.getCode()); // 使用 getCode() 获取 int 值
            rating.setRatedId(article.getApplyId());
        } else if (article.getApplyId().equals(rating.getRaterId())) {
            rating.setRatingRole(RatingRole.PARTICIPANT_TO_PUBLISHER.getCode()); // 同上
            rating.setRatedId(article.getUserId());
        }

        // 4. 校验用户角色和评价权限
        checkRatingPermission(rating, article);

        // 5. 检查是否重复评价
        if (hasRated(rating.getArticleId(), rating.getRaterId(), rating.getRatingRole())) {
            throw new CampusException("您已经评价过该活动", 201);
        }

        // 6. 设置评价默认信息
        rating.setId(RandomUtil.generateId());
        rating.setCreateTime(LocalDateTime.now());
        rating.setUpdateTime(LocalDateTime.now());
        rating.setDeleted(false);

        // 7. 保存评价记录
        boolean saveResult = save(rating);
        if (!saveResult) {
            throw new CampusException("评价保存失败", 201);
        }
        // 8. 更新信用值
//        userScoreService.updateCommentAverage(rating.getRatedId(), getCommentAverage(rating.getRatedId()));

//        // 8. 发送评价通知
//        UserInfoVo userInfoVo = UserContext.getUser();
//        sendRatingNotification(userInfoVo.getId(), userInfoVo.getUserName(), rating.getScore(), article.getTitle(), userInfoVo.getId().equals(article.getUserId()));
        return true;
    }


    /**
     * 获取用户评价的平均分
     *
     * @param userId 用户ID
     * @return 保留一位小数的平均评分，如果无评价记录则返回0.0
     */
    private Double getCommentAverage(String userId) {
        // 构建查询条件，根据用户ID查询所有评价记录
        LambdaQueryWrapper<ActivityRating> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ActivityRating::getRatedId, userId);
        List<ActivityRating> ratings = list(queryWrapper);

        // 如果无评价记录则返回0.0
        if (ratings.isEmpty()) {
            return 0.0;
        }

        // 计算所有评价的总分并求出平均分，最后保留一位小数
        double sum = ratings.stream().mapToDouble(ActivityRating::getScore).sum();
        double average = sum / ratings.size();
        return Math.round(average * 10) / 10.0;
    }

    /**
     * 发送评价通知（区分评价者身份：申请人或发布人）
     *
     * @param ratedUserId   被评价用户的ID
     * @param raterNickname 评价者昵称
     * @param ratingScore   评分（1-5）
     * @param articleTitle  活动标题
     * @param isPublisher   是否为发布者（true = 发布者，false = 申请人）
     */
    public void sendRatingNotification(String ratedUserId, String raterNickname, int ratingScore, String articleTitle, boolean isPublisher) {
        String title, content;

        // 确定评价角色
        String role = isPublisher ? "发布者" : "申请人";

        // 根据评分确定评价类型
        if (ratingScore >= 4) {
            title = "收到好评";
            content = "您作为" + role + "在活动《" + articleTitle + "》中被 " + raterNickname + " 给予了好评，感谢您的出色表现！";
        } else if (ratingScore == 3) {
            title = "收到中评";
            content = "您作为" + role + "在活动《" + articleTitle + "》中被 " + raterNickname + " 给予了中评，请继续保持努力！";
        } else {
            title = "收到差评";
            content = "您作为" + role + "在活动《" + articleTitle + "》中被 " + raterNickname + " 给予了差评，建议及时改进服务或沟通方式。";
        }

//        activityApplyService.sendSystemNotification(ratedUserId, title, content,);
    }

    /**
     * 更新评价
     */
    public boolean updateRating(ActivityRating rating) {
        return updateById(rating);
    }

    /**
     * 删除评价（逻辑删除）
     */
    public boolean deleteRating(String id) {
        return removeById(id);
    }

    /**
     * 获取所有评价列表
     */
    public List<ActivityRating> getAllRatings() {
        return list();
    }

    /**
     * 根据ID获取评价详情
     */
    public ActivityRating getRatingById(String id) {
        return getById(id);
    }

    /**
     * 查询我发布的待评价活动
     */
    @Override
    public IPage<ActivityArticleVo> getPublishedToRate(Page<ActivityArticleVo> pageParam, String currentUserId) {
        return baseMapper.selectPublishedToRate(pageParam, currentUserId);
    }

    /**
     * 查询我参与的待评价活动
     */
    @Override
    public IPage<ActivityArticleVo> getParticipatedToRate(Page<ActivityArticleVo> pageParam, String currentUserId) {
        return baseMapper.selectParticipatedToRate(pageParam, currentUserId);
    }

    @Override
    public Result<?> deleteViewRating(ActivityRating rating) {
        ActivityArticle article = activityArticleService.getById(rating.getArticleId());
        if (article == null) {
            throw new CampusException("活动不存在", 201);
        }
        // 判断是接单人还是发布人
        if (article.getApplyId().equals(UserContext.getUser().getId())) {
            article.setRatingViewStatus("1");
        } else if (article.getUserId().equals(UserContext.getUser().getId())) {
            article.setRatingViewStatus("0");
        }
        article.setUpdateTime(LocalDateTime.now());
        activityArticleService.updateById(article);

        return Result.success("删除成功");
    }

    /**
     * 处理活动评价的阅读状态更新
     *
     * @param rating 活动评价对象，包含文章ID等信息
     * @return Result<?> 操作结果，成功时返回成功消息
     */
    public Result<?> readRating(ActivityRatingDto rating) {
        String type = rating.getType();
        List<ActivityArticle> articles;

        if (RatingConstants.TYPE_PUBLISHER.equals(type)) {
            articles = baseMapper.selectPublishedListToRate(UserContext.getUser().getId());
            articles.forEach(article ->
                    article.setRatingReadStatus(
                            RatingConstants.STATUS_APPLICANT_READ.equals(article.getRatingReadStatus())
                                    ? RatingConstants.STATUS_BOTH_READ
                                    : RatingConstants.STATUS_PUBLISHER_READ
                    )
            );
        } else if (RatingConstants.TYPE_PARTICIPANT.equals(type)) {
            articles = baseMapper.selectParticipatedListToRate(UserContext.getUser().getId());
            articles.forEach(article ->
                    article.setRatingReadStatus(
                            RatingConstants.STATUS_PUBLISHER_READ.equals(article.getRatingReadStatus())
                                    ? RatingConstants.STATUS_BOTH_READ
                                    : RatingConstants.STATUS_APPLICANT_READ
                    )
            );
        } else {
            return Result.fail(" 未知类型");
        }

        // 批量更新（MyBatis-Plus）
        activityArticleService.updateBatchById(articles);
        return Result.success("已读成功");
    }


    /**
     * 评价参数校验
     */
    private void validateRating(ActivityRating rating) throws CampusException {
        if (rating == null) {
            throw new CampusException("评价信息不能为空", 201);
        }
        if (StringUtils.isBlank(rating.getArticleId())) {
            throw new CampusException("活动ID不能为空", 201);
        }
        if (StringUtils.isBlank(rating.getRaterId())) {
            throw new CampusException("评价人ID不能为空", 201);
        }
        if (rating.getScore() == 0 || rating.getScore() < 1 || rating.getScore() > 5) {
            throw new CampusException("评分必须在1-5之间", 201);
        }
    }

    /**
     * 检查活动是否可评价
     */
    private boolean canRateArticle(ActivityArticle article) {
        // 只有已完成的活动可以评价（根据您的status=3表示已完成）
        return article.getStatus() != null && article.getStatus().equals("3");
    }

    /**
     * 检查评价权限
     */
    private void checkRatingPermission(ActivityRating rating, ActivityArticle article)
            throws CampusException {

        // 验证评价人与被评价人关系
        if (rating.getRatingRole() == RatingRole.PUBLISHER_TO_PARTICIPANT.getCode()) {
            // 发布者评价参与者：评价人必须是活动发布者
            if (!rating.getRaterId().equals(article.getUserId())) {
                throw new CampusException("只有活动发布者可以评价参与者", 201);
            }
            // 被评价人必须是活动参与者
            if (!rating.getRatedId().equals(article.getApplyId())) {
                throw new CampusException("被评价人不是该活动的参与者", 201);
            }
        } else if (rating.getRatingRole() == RatingRole.PARTICIPANT_TO_PUBLISHER.getCode()) {
            // 参与者评价发布者：评价人必须是活动参与者
            if (!rating.getRaterId().equals(article.getApplyId())) {
                throw new CampusException("只有活动参与者可以评价发布者", 201);
            }
            // 被评价人必须是活动发布者
            if (!rating.getRatedId().equals(article.getUserId())) {
                throw new CampusException("被评价人不是该活动的发布者", 201);
            }
        } else {
            throw new CampusException("非法的评价角色类型", 201);
        }
    }

    /**
     * 检查是否已评价
     */
    private boolean hasRated(String articleId, String raterId, int role) {
        LambdaQueryWrapper<ActivityRating> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ActivityRating::getArticleId, articleId)
                .eq(ActivityRating::getRaterId, raterId)
                .eq(ActivityRating::getRatingRole, role);
        return count(queryWrapper) > 0;
    }
}
